Next: Lexical Binding, Previous: Dynamic Binding, Up: Variable Scoping [Contents][Index]
Dynamic binding is a powerful feature, as it allows programs to refer to variables that are not defined within their local textual scope. However, if used without restraint, this can also make programs hard to understand. There are two clean ways to use this technique:
let form where the variable was bound. If this
convention is followed consistently throughout a program, the
value of the variable will not affect, nor be affected by, any
uses of the same variable symbol elsewhere in the program.defvar,
defconst, or defcustom. See
Defining
Variables. Usually, the definition should be at top-level
in an Emacs Lisp file. As far as possible, it should include
a documentation string which explains the meaning and purpose
of the variable. You should also choose the variable’s
name to avoid name conflicts (see Coding
Conventions).
Then you can bind the variable anywhere in a program, knowing reliably what the effect will be. Wherever you encounter the variable, it will be easy to refer back to the definition, e.g., via the C-h v command (provided the variable definition has been loaded into Emacs). See Name Help in The GNU Emacs Manual.
For example, it is common to use local bindings for
customizable variables like
case-fold-search:
(defun search-for-abc ()
"Search for the string \"abc\", ignoring case differences."
(let ((case-fold-search nil))
(re-search-forward "abc")))
Next: Lexical Binding, Previous: Dynamic Binding, Up: Variable Scoping [Contents][Index]